﻿using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraTab;
using Lamex.Base;
using Lamex.Interface;
using Lamex.Library;
using Lamex.Library.CommonClass;
using Lamex.SIESystemManager.BLL;
using Lamex.SIESystemManager.Calculate;
using Lamex.SIESystemManager.ucControls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;


namespace Lamex.SIESystemManager.UI
{
    public partial class FrmBIEGroupPackageData : frmBaseDataForm
    {
        public FrmBIEGroupPackageData()
        {
            InitializeComponent();
            InitializeForm();
            DateEditFormat();
            this.Load += new EventHandler(FrmBIEGroupPackageData_Load);

        }
        protected override void InitializeForm()
        {
            ShowSummary(); //下载显示数据.

        }
        //BOM版本
        public DataTable GetBOMVer()
        {
            DataTable dt = new DataTable();
            string sql = @"select DISTINCT Version from [dbo].[B_IE_PACKAGE_MASTER_DATA_STD]
  ORDER BY Version DESC";
            dt = BaseBuildSql.GetDataTableBySql(sql);
            return dt;
        }
        public void DateEditFormat()
        {
            cbBOM.Properties.Items.Clear();
            foreach (DataRow row in GetBOMVer().Rows)
            {
                cbBOM.Properties.Items.Add(row["Version"]);
            }
            cbBOM.SelectedIndex = 0;
        }
        private void FrmBIEGroupPackageData_Load(object sender, EventArgs e)
        {
            try { this.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
        }
        private void ShowSummary()
        {
            try
            {
                xtraTabPage2.PageEnabled = false;
                xtraTabPage1.PageEnabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 标准查询
        /// </summary>
        /// <param name="sender"></param>
        public override void DoSTD(Lamex.Interface.IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_WorkTimeHistory", "LamexMESManager")) return;
            #endregion

            SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
            List<string> errorList = new List<string>();//保存错误值
            GetWorkHourTable Table = new GetWorkHourTable();
            GetOperation_Data getBOM = new GetOperation_Data();
            C_BOM_Routing c_Bom = new C_BOM_Routing();
            C_Routing_Group c_routing = new C_Routing_Group();
            C_D44 c_d44 = new C_D44();
            C_D47 c_d47 = new C_D47();
            C_D51 c_d51 = new C_D51();
            C_D54 c_d54 = new C_D54();
            //DataTable dtWork_Time = getBOM.GetIEWorkTime_BOM();//工时保存表
            DataTable dtBom_Master = getBOM.GetBOM_MASTER(cbBOM.Text);//主数据
            DataTable dtBom = getBOM.GetBOM(cbBOM.Text);//BOM表
            DataTable dtBom_NECESSARY = getBOM.GetBOM_NECESSARY();//BOM特征适用表
            DataTable dtOptertion = c_Bom.GetTable_Temp();//生成特征表
            DataTable dtNew = Table.GetTable_BOM();//定义-动态生成输出表
            DataTable dtFactor = getBOM.GetFactor(DateTime.Now.ToString("yyyy-MM-dd"));//获取宽放系数--增加生效时间
            DataRow dr = dtNew.NewRow();//定义-动态生成输出行
            DataTable dt = new DataTable();//保存特征数据
            Dictionary<string, string> dic_Routing = new Dictionary<string, string>();//保存工艺路线          
            DataTable dtAction = getBOM.GetOperationSql(DateTime.Now.ToString("yyyy-MM-dd"));//动作定义表
            double TD44 = 0, TD47 = 0, TD51 = 0, TD54 = 0;
            List<double> RoutingList = new List<double>();//代码组描述
            string Routing_dec = "";
            bool first = true;//用于判断是否第一次执行
            int Serial = 0, Routing_Group = 0, Calculate = 0;//代码组和流水号计数
            DataTable dtSerial = getBOM.GetRouting();
            DataRow drser = dtSerial.Select("1=1", "IDNO ASC").LastOrDefault();//主表最后一行数据
            DataTable dtRouting = c_routing.GetTable_Routing();//工艺路线流水号输出表
            DataRow drRouting = dtRouting.NewRow();//路线代码组输出表
            DataTable Routing_JM = getBOM.GetRouting_JM();//工艺路线简码
            int sucess = 0, fail = 0;
            //特殊处理 之前把不是44组别的也查出来，往后累计，导致组别异常，但是出现异常的组别不能重新增加，需要保留，后续新的才新增
            DataTable dtSerialTemp = getBOM.GetRouting_Temp();
            try
            {

                //using (DevExpress.Utils.WaitDialogForm wdf = new DevExpress.Utils.WaitDialogForm("请稍等", "正在计算保存标准数据...", new Size(400, 80)))
                //{
                DataView dv = dtBom_Master.DefaultView;
                DataTable DistTable = dv.ToTable(true, "MATERIAL_NO", "PRODUCT_DI", "SIZE");
                for (int i = 0; i < DistTable.Rows.Count; i++)
                {
                    //SIZE为空,不为空则不计算
                    if (DistTable.Rows[i]["SIZE"].ToString().Length > 1)
                    {
                        string InserError = @"insert into [LamexMESManager].[dbo].[B_IE_BOM_ERRORINFO] ([Mater_No],[Create_TS],[Falg],[Describes]) values('" + DistTable.Rows[i]["MATERIAL_NO"].ToString() + "',GETDATE(),'3','SIZE不为空')";
                        int t = BaseBuildSql.ExecuteNonQuery(InserError);
                        errorList.Add(DistTable.Rows[i]["MATERIAL_NO"].ToString());
                        fail++;
                        continue;
                    }
                    //获取工艺路线
                    string Routing = c_Bom.GetRouting(DistTable.Rows[i]["PRODUCT_DI"].ToString(),
                        dtBom.Select("MATERIAL_NO='" + DistTable.Rows[i]["MATERIAL_NO"].ToString() + "'").Length > 0 ?
                        dtBom.Select("MATERIAL_NO='" + DistTable.Rows[i]["MATERIAL_NO"].ToString() + "'").CopyToDataTable() : null);
                    //获取动作名称
                    List<string> OptertionList = c_Bom.GetOperation(Routing, DateTime.Now.ToString("yyyy-MM-dd"));
                    //主数据和BOM表的交集
                    DataTable dtcontrast = new DataTable();
                    dtcontrast = c_Bom.DataTableContrast(dtBom.Select("MATERIAL_NO='" + DistTable.Rows[i]["MATERIAL_NO"].ToString() + "'").Length > 0 ?
                        dtBom.Select("MATERIAL_NO='" + DistTable.Rows[i]["MATERIAL_NO"].ToString() + "'").CopyToDataTable() : null,
                        dtBom_NECESSARY);
                    //获取动作特征
                    dt = c_Bom.GetOPeration_Values("BOM_ST", DistTable.Rows[i]["MATERIAL_NO"].ToString(), OptertionList, Routing, dtcontrast, dtBom, dtOptertion, dtBom_NECESSARY);
                    //保存工艺路线
                    dic_Routing.Add(DistTable.Rows[i]["MATERIAL_NO"].ToString(), Routing);


                }
                //先删除数据库存在的
                StringBuilder sbFilter1 = new StringBuilder();
                List<string> delete1 = new List<string>();//删除重复B_IE_Operation_Data
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        delete1.Add(dt.Rows[i][0].ToString());
                    }
                    sbFilter1.AppendFormat(@"  DRAWING_NUMBER IN ('{0}')", string.Join("','", delete1.ToArray()));
                    string sqlDel1 = @"Delete  FROM [LamexMESManager].[dbo].[B_IE_Operation_Data] where " + sbFilter1 + "";
                    int n = BaseBuildSql.ExecuteNonQuery(sqlDel1);

                }
                //批量插入数据库B_IE_Machine_Time
                if (BaseBuildSql.ExcuteInsert(dt, "B_IE_Operation_Data"))
                {
                    if (dt.Rows.Count > 0)
                    {
                        //工时计算
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            #region 插入行 工时结果表
                            dr = dtNew.NewRow();
                            dr["PartNumber"] = dt.Rows[i]["DRAWING_NUMBER"].ToString();//部件号                 
                            dr["WorkCenterNumber"] = dic_Routing[dt.Rows[i]["DRAWING_NUMBER"].ToString()];//工艺路线
                            dr["Decription"] = dtBom_Master.Select("MATERIAL_NO='" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "'").CopyToDataTable().Rows[0]["DESCRIBES"];//部件描述                        
                            //dr["Cycle"] = 30;//周期
                            dr["CreateDate"] = DateTime.Now;
                            dr["Flag"] = "3";
                            string[] ListRouting = dr["WorkCenterNumber"].ToString().Split('-');//得到图纸的工艺路线
                            foreach (var item in ListRouting)
                            {
                                switch (item.ToString())
                                {
                                    case "D44":
                                        TD44 = Math.Ceiling(c_d44.GetD44(dt.Select("DRAWING_NUMBER='" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "'"), dtAction.Select("WORKSTATION_LIST like '%D44%'"))
                                        * (dtFactor.Select("PROCESS_CODE='D44'").Length <= 0 ? 1 :
                                         1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D44'"))[0].ItemArray[1].ToString())));
                                        dr["D44"] = TD44;
                                        RoutingList.Add(TD44);
                                        break;
                                    case "D47":
                                        TD47 = Math.Ceiling(c_d47.GetD47(dt.Select("DRAWING_NUMBER='" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "'"), dtAction.Select("WORKSTATION_LIST like '%D47%'"))
                                        * (dtFactor.Select("PROCESS_CODE='D47'").Length <= 0 ? 1 :
                                        1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D47'"))[0].ItemArray[1].ToString())));
                                        dr["D47"] = TD47;
                                        RoutingList.Add(TD47);
                                        break;
                                    case "D51":
                                        TD51 = Math.Ceiling(c_d51.GetD51(dt.Select("DRAWING_NUMBER='" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "'"), dtAction.Select("WORKSTATION_LIST like '%D51%'"))
                                        * (dtFactor.Select("PROCESS_CODE='D51'").Length <= 0 ? 1 :
                                         1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D51'"))[0].ItemArray[1].ToString())));
                                        dr["D51"] = TD51;
                                        RoutingList.Add(TD51);
                                        break;
                                    case "D54":
                                        TD54 = Math.Ceiling(c_d54.GetD54(dt.Select("DRAWING_NUMBER='" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "'"), dtAction.Select("WORKSTATION_LIST like '%D54%'"))
                                        * (dtFactor.Select("PROCESS_CODE='D54'").Length <= 0 ? 1 :
                                        1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D54'"))[0].ItemArray[1].ToString())));
                                        dr["D54"] = TD54;
                                        RoutingList.Add(TD54);
                                        break;

                                }
                            }

                            #endregion
                            #region 工艺代码组赋值
                            if (RoutingList.Count == 0)
                            {
                                //DevExpress.XtraEditors.XtraMessageBox.Show("该部件号:" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "无工艺路线简码，请检测确认！", "提示", MessageBoxButtons.OK);
                                //return;
                                string InserError = @"insert into [LamexMESManager].[dbo].[B_IE_BOM_ERRORINFO] ([Mater_No],[Create_TS],[Falg],[Describes]) values('" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "',GETDATE(),'3','无工艺路线简码')";
                                int t = BaseBuildSql.ExecuteNonQuery(InserError);
                                errorList.Add(dt.Rows[i]["DRAWING_NUMBER"].ToString());
                                fail++;
                                continue;
                            }
                            if (Routing_JM.Select("GROUP_ROUTING='" + dr["WorkCenterNumber"] + "'").Length <= 0)
                            {
                                string InserError = @"insert into [LamexMESManager].[dbo].[B_IE_BOM_ERRORINFO] ([Mater_No],[Create_TS],[Falg],[Describes]) values('" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "',GETDATE(),'3','无工艺路线简码')";
                                int t = BaseBuildSql.ExecuteNonQuery(InserError);
                                errorList.Add(dt.Rows[i]["DRAWING_NUMBER"].ToString());
                                fail++;
                                continue;
                            }
                            foreach (var list in RoutingList)
                            {
                                Routing_dec += list + "_";
                            }
                            dr["CountDecription"] = Routing_JM.Select("GROUP_ROUTING='" + dr["WorkCenterNumber"] + "'")[0].ItemArray[0].ToString() + "_" + Routing_dec.Substring(0, Routing_dec.Length - 1);//代码组描述
                            if (dr["CountDecription"].ToString().Contains("D075"))
                                dr["Cycle"] = 30;//周期
                            else
                                dr["Cycle"] = 0;//周期
                            //获取计数流水和组别
                            // int[] routings = c_routing.GetNumber(dr["CALCULATE_DESC"].ToString());                        
                            //DataRow drser = dtSerial.Select("1=1", "IDNO ASC").LastOrDefault();//主表最后一行数据
                            DataRow drTemp = dtRouting.Select("1=1", "Serial ASC").LastOrDefault();//临时表最后一行数据
                            drRouting = dtRouting.NewRow();//路线代码组输出表   
                            DataRow[] drTemp2 = dtSerial.Select("Calculate_Desc='" + dr["CountDecription"] + "'");//主表
                            DataRow[] drTemp1 = dtRouting.Select("Calculate_Desc='" + dr["CountDecription"] + "'");//临时表
                            DataRow[] drTemp3 = dtSerialTemp.Select("Calculate_Desc='" + dr["CountDecription"] + "'");//主表-特殊计算 后续可删除
                            if (drTemp3.Length > 0)
                            {
                                dr["GROUP_CODE"] = drTemp3[0]["Routing_Group"];
                                dr["iCount"] = drTemp3[0]["Calculate"];
                            }
                            else if (drTemp2.Length > 0)
                            {

                                dr["GROUP_CODE"] = drTemp2[0]["Routing_Group"];
                                dr["iCount"] = drTemp2[0]["Calculate"];
                            }
                            else
                            {
                                if (drTemp1.Length > 0)
                                {

                                    dr["GROUP_CODE"] = drTemp1[0]["Routing_Group"];
                                    dr["iCount"] = drTemp1[0]["Calculate"];

                                }
                                else
                                {
                                    if (first)
                                    {
                                        Serial = 1;
                                        if (drser != null)
                                        {
                                            if (Convert.ToInt32(drser["Calculate"]) >= 2 && Convert.ToInt32(drser["Calculate"]) < 99)
                                            {
                                                drRouting["Routing_Group"] = Convert.ToInt32(drser["Routing_Group"]);
                                                drRouting["Calculate"] = Convert.ToInt32(drser["Calculate"]) + 1;

                                            }
                                            else if (Convert.ToInt32(drser["Calculate"]) == 99)
                                            {
                                                drRouting["Routing_Group"] = Convert.ToInt32(drser["Routing_Group"]) + 1;
                                                drRouting["Calculate"] = 2;
                                            }
                                        }
                                        else
                                        {
                                            drRouting["Routing_Group"] = 44000001;
                                            drRouting["Calculate"] = 2;
                                        }
                                        dr["GROUP_CODE"] = drRouting["Routing_Group"];
                                        dr["iCount"] = drRouting["Calculate"];
                                        Routing_Group = Convert.ToInt32(drRouting["Routing_Group"]);
                                        Calculate = Convert.ToInt32(drRouting["Calculate"]);
                                    }
                                    else
                                    {
                                        Serial = Convert.ToInt32(drTemp["Serial"]) + 1;
                                        if (drTemp != null)
                                        {
                                            if (Convert.ToInt32(drTemp["Calculate"]) >= 2 && Convert.ToInt32(drTemp["Calculate"]) < 99)
                                            {
                                                drRouting["Routing_Group"] = Convert.ToInt32(drTemp["Routing_Group"]);
                                                drRouting["Calculate"] = Convert.ToInt32(drTemp["Calculate"]) + 1;

                                            }
                                            else if (Convert.ToInt32(drTemp["Calculate"]) == 99)
                                            {
                                                drRouting["Routing_Group"] = Convert.ToInt32(drTemp["Routing_Group"]) + 1;
                                                drRouting["Calculate"] = 2;
                                            }
                                        }
                                        else
                                        {
                                            drRouting["Routing_Group"] = 44000001;
                                            drRouting["Calculate"] = 2;
                                        }
                                        dr["GROUP_CODE"] = drRouting["Routing_Group"];
                                        dr["iCount"] = drRouting["Calculate"];
                                        Routing_Group = Convert.ToInt32(drRouting["Routing_Group"]);
                                        Calculate = Convert.ToInt32(drRouting["Calculate"]);
                                    }
                                    //}
                                    //存在的数据不需要插入到数据库
                                    // drRouting = dtRouting.NewRow();//路线代码组输出表                     
                                    drRouting["Serial"] = Serial;
                                    drRouting["Routing_Group"] = Routing_Group;
                                    drRouting["Calculate"] = Calculate;
                                    drRouting["Calculate_Desc"] = dr["CountDecription"];
                                    drRouting["Date_TS"] = DateTime.Now;
                                    drRouting["Update_User"] = Lamex.Common.Loginer.CurrentUser.AccountName;
                                    dtRouting.Rows.Add(drRouting);
                                    first = false;
                                }
                            }
                            #endregion
                            dtNew.Rows.Add(dr);
                            #region 插入临时表后数据全部初始化为0
                            TD44 = 0;
                            TD47 = 0;
                            TD51 = 0;
                            TD54 = 0;
                            RoutingList = new List<double>();
                            Routing_dec = "";
                            Serial = 0;
                            Routing_Group = 0;
                            Calculate = 0;
                            #endregion
                            sucess++;
                        }
                    }

                }
                //工艺路线流水号批量插入主表-B_IE_Calculator_Routing

                if (BaseBuildSql.ExcuteInsert(dtRouting, "B_IE_Calculator_Routing"))
                {

                    dtRouting = new DataTable();
                }
                //工时保存--重复的删除
                // DataTable dtDelete = c_Bom.DataTableContrast_TIME(dtWork_Time, dtNew);
                StringBuilder sbFilter = new StringBuilder();
                StringBuilder sbFilterMaterial = new StringBuilder();
                List<string> delete = new List<string>();
                if (dtNew.Rows.Count > 0)
                {
                    for (int i = 0; i < dtNew.Rows.Count; i++)
                    {
                        delete.Add(dtNew.Rows[i][0].ToString());
                    }
                    sbFilter.AppendFormat(@"  PartNumber IN ('{0}')", string.Join("','", delete.ToArray()));
                    sbFilterMaterial.AppendFormat(@"  MATERIAL_NO IN ('{0}')", string.Join("','", delete.ToArray()));
                    string sqlDel = @"Delete  FROM [LamexMESManager].[dbo].[B_IE_WorkTimeHistory] where " + sbFilter + "";
                    int n = BaseBuildSql.ExecuteNonQuery(sqlDel);
                    //插入特征表后更新标识
                    string updateSql = @"update [LamexMESManager].[dbo].[B_IE_PACKAGE_MASTER_DATA_STD] set CALCULATE_FLAG=1,CALCULATE_TS=GETDATE() where  " + sbFilterMaterial + " ";
                    int m = BaseBuildSql.ExecuteNonQuery(updateSql);
                }
                if (BaseBuildSql.ExcuteInsert(dtNew, "B_IE_WorkTimeHistory"))
                {

                }


                //显示BOM主数据
                gridControl2.DataSource = dt;
                gridView2.BestFitColumns();
                this.gridView2.OptionsView.ColumnAutoWidth = false;

                DevExpress.XtraEditors.XtraMessageBox.Show("共【" + DistTable.Rows.Count + "】条！成功【" + sucess + "】条！失败【" + fail + "】条！", "提示", MessageBoxButtons.OK);
                if (errorList.Count > 0)
                {
                    StringBuilder sbFilter2 = new StringBuilder();
                    sbFilter2.AppendFormat(@"  Mater_No IN ('{0}')", string.Join("','", errorList.ToArray()));
                    //导出错误列表
                    if (!Directory.Exists(@"D:\MESTemp"))
                        Directory.CreateDirectory(@"D:\MESTemp");
                    SaveFileDialog fileDialog = new SaveFileDialog();
                    fileDialog.Title = "导出错误列表";
                    fileDialog.InitialDirectory = @"D:\MESTemp\";//导出默认路径
                    fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";//导出默认格式
                    fileDialog.FileName = "MES_TEMP_" + DateTime.Now.ToString("yyMMdd_hhMMss");//导出默认名称                                                                                                                               
                    string sql = @"SELECT distinct
       [Mater_No] as PartNo
      ,[Drawing_No]
      ,[Describes]
      --,[Create_TS]
  FROM[LamexMESManager].[dbo].[B_IE_BOM_ERRORINFO]
  where 1=1 AND " + sbFilter2 + " ";
                    DataTable dtTemp = BaseBuildSql.GetDataTableBySql(sql);
                    GridControl grid = new GridControl();
                    GridView view = new GridView();
                    grid.ViewCollection.Add(view);
                    grid.MainView = view;
                    view.GridControl = grid;
                    foreach (DataColumn dc in dtTemp.Columns)
                    {
                        DevExpress.XtraGrid.Columns.GridColumn gridColumnNumber = view.Columns.AddVisible(dc.ColumnName);
                        gridColumnNumber.FieldName = dc.ColumnName;
                    }
                    grid.DataSource = dtTemp;
                    this.Controls.Add(grid);
                    grid.ForceInitialize();//强制初始化           
                    view.BestFitColumns();
                    view.OptionsView.ColumnAutoWidth = false;
                    view.OptionsView.ShowAutoFilterRow = false;
                    view.OptionsPrint.PrintHorzLines = false;//去掉水平网格线
                    view.OptionsPrint.PrintVertLines = false;//去掉垂直网格线
                    view.ExportToXlsx(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");
                    //if (DevExpress.XtraEditors.XtraMessageBox.Show("生成错误信息列表成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    System.Diagnostics.Process.Start(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");//打开指定路径下的文件

                }
                dtNew = new DataTable();
                dt = new DataTable();
                errorList = new List<string>();
                ////执行储存过程--工时数据更新到IE_Part_ProcessTime
                //List<string> lst1 = new List<string>();
                //lst1.Add("1");
                //BaseBuildSql.GetProDataTable("p_IE_IED_TransForm", lst1);
                SplashScreenTool.CloseSplashScreen();
               
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
                SplashScreenTool.CloseSplashScreen();
            }



        }
        /// <summary>
        /// SJ查询
        /// </summary>
        /// <param name="sender"></param>
        public override void DoSJ(Lamex.Interface.IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_WorkTimeHistory", "LamexMESManager")) return;
            #endregion
            SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
            List<string> errorList = new List<string>();
            GetWorkHourTable Table = new GetWorkHourTable();
            GetOperation_Data getBOM = new GetOperation_Data();
            C_BOM_Routing c_Bom = new C_BOM_Routing();
            C_Routing_Group c_routing = new C_Routing_Group();
            C_D44 c_d44 = new C_D44();
            C_D47 c_d47 = new C_D47();
            C_D51 c_d51 = new C_D51();
            C_D54 c_d54 = new C_D54();
            // DataTable dtWork_Time = getBOM.GetIEWorkTime_BOM();//工时保存表
            DataTable dtBom_Master = getBOM.GetBOM_MASTERSJ();//主数据
            DataTable dtBom = getBOM.GetBOMSJ();//BOM表
            DataTable dtBom_NECESSARY = getBOM.GetBOM_NECESSARY();//BOM特征适用表
            DataTable dtOptertion = c_Bom.GetTable_Temp();//生成特征表
            DataTable dtNew = Table.GetTable_BOM();//定义-动态生成输出表
            DataTable dtFactor = getBOM.GetFactor(DateTime.Now.ToString("yyyy-MM-dd"));//获取宽放系数--增加生效时间
            DataRow dr = dtNew.NewRow();//定义-动态生成输出行
            DataTable dt = new DataTable();//保存特征数据
            Dictionary<string, string> dic_Routing = new Dictionary<string, string>();//保存工艺路线          
            DataTable dtAction = getBOM.GetOperationSql(DateTime.Now.ToString("yyyy-MM-dd"));//动作定义表
            double TD44 = 0, TD47 = 0, TD51 = 0, TD54 = 0;
            List<double> RoutingList = new List<double>();//代码组描述
            string Routing_dec = "";
            bool first = true;//用于判断是否第一次执行
            int Serial = 0, Routing_Group = 0, Calculate = 0;//代码组和流水号计数
            DataTable dtSerial = getBOM.GetRouting();
            DataRow drser = dtSerial.Select("1=1", "IDNO ASC").LastOrDefault();//主表最后一行数据
            DataTable dtRouting = c_routing.GetTable_Routing();//工艺路线流水号输出表
            DataRow drRouting = dtRouting.NewRow();//路线代码组输出表
            DataTable Routing_JM = getBOM.GetRouting_JM();//工艺路线简码
            int sucess = 0, fail = 0;//定义保存成功/失败计数
            //特殊处理 之前把不是44组别的也查出来，往后累计，导致组别异常，但是出现异常的组别不能重新增加，需要保留，后续新的才新增
            DataTable dtSerialTemp = getBOM.GetRouting_Temp();
            try
            {

                //using (DevExpress.Utils.WaitDialogForm wdf = new DevExpress.Utils.WaitDialogForm("请稍等", "正在计算保存SJ数据...", new Size(400, 80)))
                //{
                DataView dv = dtBom_Master.DefaultView;
                DataTable DistTable = dv.ToTable(true, "MATERIAL_NO", "PRODUCT_DI", "SIZE");
                for (int i = 0; i < DistTable.Rows.Count; i++)
                {
                    //SIZE为空,不为空则不计算
                    if (DistTable.Rows[i]["SIZE"].ToString().Length > 1)
                    {
                        string InserError = @"insert into [LamexMESManager].[dbo].[B_IE_BOM_ERRORINFO] ([Mater_No],[Create_TS],[Falg],[Describes]) values('" + DistTable.Rows[i]["MATERIAL_NO"].ToString() + "',GETDATE(),'4','SIZE不为空')";
                        int t = BaseBuildSql.ExecuteNonQuery(InserError);
                        errorList.Add(DistTable.Rows[i]["MATERIAL_NO"].ToString());
                        fail++;
                        continue;
                    }
                    //获取工艺路线
                    string Routing = c_Bom.GetRouting(DistTable.Rows[i]["PRODUCT_DI"].ToString(),
                        dtBom.Select("MATERIAL_NO='" + DistTable.Rows[i]["MATERIAL_NO"].ToString() + "'").Length > 0 ?
                        dtBom.Select("MATERIAL_NO='" + DistTable.Rows[i]["MATERIAL_NO"].ToString() + "'").CopyToDataTable() : null);
                    //获取动作名称
                    List<string> OptertionList = c_Bom.GetOperation(Routing, DateTime.Now.ToString("yyyy-MM-dd"));
                    //主数据和BOM表的交集
                    DataTable dtcontrast = new DataTable();
                    dtcontrast = c_Bom.DataTableContrast(dtBom.Select("MATERIAL_NO='" + DistTable.Rows[i]["MATERIAL_NO"].ToString() + "'").Length > 0 ?
                        dtBom.Select("MATERIAL_NO='" + DistTable.Rows[i]["MATERIAL_NO"].ToString() + "'").CopyToDataTable() : null,
                        dtBom_NECESSARY);
                    //获取动作特征
                    dt = c_Bom.GetOPeration_Values("BOM_SJ", DistTable.Rows[i]["MATERIAL_NO"].ToString(), OptertionList, Routing, dtcontrast, dtBom, dtOptertion, dtBom_NECESSARY);
                    //保存工艺路线
                    dic_Routing.Add(DistTable.Rows[i]["MATERIAL_NO"].ToString(), Routing);


                }
                //先删除数据库存在的

                StringBuilder sbFilter1 = new StringBuilder();
                List<string> delete1 = new List<string>();//删除重复B_IE_Operation_Data
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        delete1.Add(dt.Rows[i][0].ToString());
                    }
                    sbFilter1.AppendFormat(@"  DRAWING_NUMBER IN ('{0}')", string.Join("','", delete1.ToArray()));
                    string sqlDel1 = @"Delete  FROM [LamexMESManager].[dbo].[B_IE_Operation_Data] where " + sbFilter1 + "";
                    int n = BaseBuildSql.ExecuteNonQuery(sqlDel1);

                }
                //批量插入数据库B_IE_Machine_Time
                if (BaseBuildSql.ExcuteInsert(dt, "B_IE_Operation_Data"))
                {
                    if (dt.Rows.Count > 0)
                    {
                        //工时计算
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            #region 插入行 工时结果表
                            dr = dtNew.NewRow();
                            dr["PartNumber"] = dt.Rows[i]["DRAWING_NUMBER"].ToString();//部件号                 
                            dr["WorkCenterNumber"] = dic_Routing[dt.Rows[i]["DRAWING_NUMBER"].ToString()];//工艺路线
                            dr["Decription"] = dtBom_Master.Select("MATERIAL_NO='" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "'").CopyToDataTable().Rows[0]["DESCRIBES"];//部件描述                        
                            //dr["Cycle"] = 30;//周期
                            dr["CreateDate"] = DateTime.Now;
                            dr["Flag"] = "4";
                            string[] ListRouting = dr["WorkCenterNumber"].ToString().Split('-');//得到图纸的工艺路线
                            foreach (var item in ListRouting)
                            {
                                switch (item.ToString())
                                {
                                    case "D44":
                                        TD44 = Math.Ceiling(c_d44.GetD44(dt.Select("DRAWING_NUMBER='" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "'"), dtAction.Select("WORKSTATION_LIST like '%D44%'"))
                                        * (dtFactor.Select("PROCESS_CODE='D44'").Length <= 0 ? 1 :
                                         1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D44'"))[0].ItemArray[1].ToString())));
                                        dr["D44"] = TD44;
                                        RoutingList.Add(TD44);
                                        break;
                                    case "D47":
                                        TD47 = Math.Ceiling(c_d47.GetD47(dt.Select("DRAWING_NUMBER='" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "'"), dtAction.Select("WORKSTATION_LIST like '%D47%'"))
                                        * (dtFactor.Select("PROCESS_CODE='D47'").Length <= 0 ? 1 :
                                        1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D47'"))[0].ItemArray[1].ToString())));
                                        dr["D47"] = TD47;
                                        RoutingList.Add(TD47);
                                        break;
                                    case "D51":
                                        TD51 = Math.Ceiling(c_d51.GetD51(dt.Select("DRAWING_NUMBER='" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "'"), dtAction.Select("WORKSTATION_LIST like '%D51%'"))
                                        * (dtFactor.Select("PROCESS_CODE='D51'").Length <= 0 ? 1 :
                                         1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D51'"))[0].ItemArray[1].ToString())));
                                        dr["D51"] = TD51;
                                        RoutingList.Add(TD51);
                                        break;
                                    case "D54":
                                        TD54 = Math.Ceiling(c_d54.GetD54(dt.Select("DRAWING_NUMBER='" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "'"), dtAction.Select("WORKSTATION_LIST like '%D54%'"))
                                        * (dtFactor.Select("PROCESS_CODE='D54'").Length <= 0 ? 1 :
                                        1 + Convert.ToDouble(dtFactor.Select(("PROCESS_CODE='D54'"))[0].ItemArray[1].ToString())));
                                        dr["D54"] = TD54;
                                        RoutingList.Add(TD54);
                                        break;

                                }
                            }
                            #endregion
                            #region 工艺代码组赋值
                            if (RoutingList.Count == 0)
                            {
                                //DevExpress.XtraEditors.XtraMessageBox.Show("该部件号:" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "无工艺路线简码，请检测确认！", "提示", MessageBoxButtons.OK);
                                //return;
                                string InserError = @"insert into [LamexMESManager].[dbo].[B_IE_BOM_ERRORINFO] ([Mater_No],[Create_TS],[Falg],[Describes]) values('" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "',GETDATE(),'4','无工艺路线简码')";
                                int t = BaseBuildSql.ExecuteNonQuery(InserError);
                                errorList.Add(dt.Rows[i]["DRAWING_NUMBER"].ToString());
                                fail++;
                                continue;
                            }
                            if (Routing_JM.Select("GROUP_ROUTING='" + dr["WorkCenterNumber"] + "'").Length <= 0)
                            {
                                string InserError = @"insert into [LamexMESManager].[dbo].[B_IE_BOM_ERRORINFO] ([Mater_No],[Create_TS],[Falg],[Describes]) values('" + dt.Rows[i]["DRAWING_NUMBER"].ToString() + "',GETDATE(),'4','无工艺路线简码')";
                                int t = BaseBuildSql.ExecuteNonQuery(InserError);
                                errorList.Add(dt.Rows[i]["DRAWING_NUMBER"].ToString());
                                fail++;
                                continue;
                            }
                            foreach (var list in RoutingList)
                            {
                                Routing_dec += list + "_";
                            }
                            dr["CountDecription"] = Routing_JM.Select("GROUP_ROUTING='" + dr["WorkCenterNumber"] + "'")[0].ItemArray[0].ToString() + "_" + Routing_dec.Substring(0, Routing_dec.Length - 1);//代码组描述
                            if (dr["CountDecription"].ToString().Contains("D075"))
                                dr["Cycle"] = 30;//周期
                            else
                                dr["Cycle"] = 0;//周期
                            //获取计数流水和组别
                            // int[] routings = c_routing.GetNumber(dr["CALCULATE_DESC"].ToString());                        
                            //DataRow drser = dtSerial.Select("1=1", "IDNO ASC").LastOrDefault();//主表最后一行数据
                            DataRow drTemp = dtRouting.Select("1=1", "Serial ASC").LastOrDefault();//临时表最后一行数据
                            drRouting = dtRouting.NewRow();//路线代码组输出表   
                            DataRow[] drTemp2 = dtSerial.Select("Calculate_Desc='" + dr["CountDecription"] + "'");//主表
                            DataRow[] drTemp1 = dtRouting.Select("Calculate_Desc='" + dr["CountDecription"] + "'");//临时表
                            DataRow[] drTemp3 = dtSerialTemp.Select("Calculate_Desc='" + dr["CountDecription"] + "'");//主表-特殊计算 后续可删除
                            if (drTemp3.Length > 0)
                            {
                                dr["GROUP_CODE"] = drTemp3[0]["Routing_Group"];
                                dr["iCount"] = drTemp3[0]["Calculate"];
                            }
                            else if (drTemp2.Length > 0)
                            {

                                dr["GROUP_CODE"] = drTemp2[0]["Routing_Group"];
                                dr["iCount"] = drTemp2[0]["Calculate"];
                            }
                            else
                            {
                                if (drTemp1.Length > 0)
                                {

                                    dr["GROUP_CODE"] = drTemp1[0]["Routing_Group"];
                                    dr["iCount"] = drTemp1[0]["Calculate"];

                                }
                                else
                                {
                                    if (first)
                                    {
                                        Serial = 1;
                                        if (drser != null)
                                        {
                                            if (Convert.ToInt32(drser["Calculate"]) >= 2 && Convert.ToInt32(drser["Calculate"]) < 99)
                                            {
                                                drRouting["Routing_Group"] = Convert.ToInt32(drser["Routing_Group"]);
                                                drRouting["Calculate"] = Convert.ToInt32(drser["Calculate"]) + 1;

                                            }
                                            else if (Convert.ToInt32(drser["Calculate"]) == 99)
                                            {
                                                drRouting["Routing_Group"] = Convert.ToInt32(drser["Routing_Group"]) + 1;
                                                drRouting["Calculate"] = 2;
                                            }
                                        }
                                        else
                                        {
                                            drRouting["Routing_Group"] = 44000001;
                                            drRouting["Calculate"] = 2;
                                        }
                                        dr["GROUP_CODE"] = drRouting["Routing_Group"];
                                        dr["iCount"] = drRouting["Calculate"];
                                        Routing_Group = Convert.ToInt32(drRouting["Routing_Group"]);
                                        Calculate = Convert.ToInt32(drRouting["Calculate"]);
                                    }
                                    else
                                    {
                                        Serial = Convert.ToInt32(drTemp["Serial"]) + 1;
                                        if (drTemp != null)
                                        {
                                            if (Convert.ToInt32(drTemp["Calculate"]) >= 2 && Convert.ToInt32(drTemp["Calculate"]) < 99)
                                            {
                                                drRouting["Routing_Group"] = Convert.ToInt32(drTemp["Routing_Group"]);
                                                drRouting["Calculate"] = Convert.ToInt32(drTemp["Calculate"]) + 1;

                                            }
                                            else if (Convert.ToInt32(drTemp["Calculate"]) == 99)
                                            {
                                                drRouting["Routing_Group"] = Convert.ToInt32(drTemp["Routing_Group"]) + 1;
                                                drRouting["Calculate"] = 2;
                                            }
                                        }
                                        else
                                        {
                                            drRouting["Routing_Group"] = 44000001;
                                            drRouting["Calculate"] = 2;
                                        }
                                        dr["GROUP_CODE"] = drRouting["Routing_Group"];
                                        dr["iCount"] = drRouting["Calculate"];
                                        Routing_Group = Convert.ToInt32(drRouting["Routing_Group"]);
                                        Calculate = Convert.ToInt32(drRouting["Calculate"]);
                                    }
                                    //}
                                    //存在的数据不需要插入到数据库
                                    // drRouting = dtRouting.NewRow();//路线代码组输出表                     
                                    drRouting["Serial"] = Serial;
                                    drRouting["Routing_Group"] = Routing_Group;
                                    drRouting["Calculate"] = Calculate;
                                    drRouting["Calculate_Desc"] = dr["CountDecription"];
                                    drRouting["Date_TS"] = DateTime.Now;
                                    drRouting["Update_User"] = Lamex.Common.Loginer.CurrentUser.AccountName;
                                    dtRouting.Rows.Add(drRouting);
                                    first = false;
                                }
                            }
                            #endregion
                            dtNew.Rows.Add(dr);
                            #region 插入临时表后数据全部初始化为0
                            TD44 = 0;
                            TD47 = 0;
                            TD51 = 0;
                            TD54 = 0;
                            RoutingList = new List<double>();
                            Routing_dec = "";
                            Serial = 0;
                            Routing_Group = 0;
                            Calculate = 0;
                            #endregion
                            sucess++;
                        }
                    }

                }
                //工艺路线流水号批量插入主表-B_IE_Calculator_Routing

                if (BaseBuildSql.ExcuteInsert(dtRouting, "B_IE_Calculator_Routing"))
                {

                    dtRouting = new DataTable();
                }
                //工时保存--重复的删除
                // DataTable dtDelete = c_Bom.DataTableContrast_TIME(dtWork_Time, dtNew);
                StringBuilder sbFilter = new StringBuilder();
                StringBuilder sbFilterMaterial = new StringBuilder();
                List<string> delete = new List<string>();
                if (dtNew.Rows.Count > 0)
                {
                    for (int i = 0; i < dtNew.Rows.Count; i++)
                    {
                        delete.Add(dtNew.Rows[i][0].ToString());
                    }
                    sbFilter.AppendFormat(@"  PartNumber IN ('{0}')", string.Join("','", delete.ToArray()));
                    sbFilterMaterial.AppendFormat(@"  MATERIAL_NO IN ('{0}')", string.Join("','", delete.ToArray()));
                    string sqlDel = @"Delete  FROM [LamexMESManager].[dbo].[B_IE_WorkTimeHistory] where " + sbFilter + "";
                    int n = BaseBuildSql.ExecuteNonQuery(sqlDel);
                    //插入特征表后更新标识
                    string updateSql = @"update [LamexMESManager].[dbo].[B_IE_PACKAGE_MASTER_DATA_SJR] set CALCULATE_FLAG=1,CALCULATE_TS=GETDATE() where  " + sbFilterMaterial + "";
                    int m = BaseBuildSql.ExecuteNonQuery(updateSql);
                }
                if (BaseBuildSql.ExcuteInsert(dtNew, "B_IE_WorkTimeHistory"))
                {

                }


                //显示BOM主数据
                gridControl2.DataSource = dt;
                gridView2.BestFitColumns();
                this.gridView2.OptionsView.ColumnAutoWidth = false;

                DevExpress.XtraEditors.XtraMessageBox.Show("共【" + DistTable.Rows.Count + "】条！成功【" + sucess + "】条！失败【" + fail + "】条！", "提示", MessageBoxButtons.OK);
                if (errorList.Count > 0)
                {
                    StringBuilder sbFilter2 = new StringBuilder();
                    sbFilter2.AppendFormat(@"  Mater_No IN ('{0}')", string.Join("','", errorList.ToArray()));
                    //导出错误列表
                    if (!Directory.Exists(@"D:\MESTemp"))
                        Directory.CreateDirectory(@"D:\MESTemp");
                    SaveFileDialog fileDialog = new SaveFileDialog();
                    fileDialog.Title = "导出错误列表";
                    fileDialog.InitialDirectory = @"D:\MESTemp\";//导出默认路径
                    fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";//导出默认格式
                    fileDialog.FileName = "MES_TEMP_" + DateTime.Now.ToString("yyMMdd_hhMMss");//导出默认名称                                                                                                                               
                    string sql = @"SELECT distinct
       [Mater_No] as PartNo
      ,[Drawing_No]
      ,[Describes]
      --,[Create_TS]
  FROM[LamexMESManager].[dbo].[B_IE_BOM_ERRORINFO]
  where 1=1 AND " + sbFilter2 + " ";
                    DataTable dtTemp = BaseBuildSql.GetDataTableBySql(sql);
                    GridControl grid = new GridControl();
                    GridView view = new GridView();
                    grid.ViewCollection.Add(view);
                    grid.MainView = view;
                    view.GridControl = grid;
                    foreach (DataColumn dc in dtTemp.Columns)
                    {
                        DevExpress.XtraGrid.Columns.GridColumn gridColumnNumber = view.Columns.AddVisible(dc.ColumnName);
                        gridColumnNumber.FieldName = dc.ColumnName;
                    }
                    grid.DataSource = dtTemp;
                    this.Controls.Add(grid);
                    grid.ForceInitialize();//强制初始化           
                    view.BestFitColumns();
                    view.OptionsView.ColumnAutoWidth = false;
                    view.OptionsView.ShowAutoFilterRow = false;
                    view.OptionsPrint.PrintHorzLines = false;//去掉水平网格线
                    view.OptionsPrint.PrintVertLines = false;//去掉垂直网格线
                    view.ExportToXlsx(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");
                    //if (DevExpress.XtraEditors.XtraMessageBox.Show("生成错误信息列表成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    System.Diagnostics.Process.Start(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");//打开指定路径下的文件

                }
                dtNew = new DataTable();
                dt = new DataTable();
                errorList = new List<string>();
                ////执行储存过程--工时数据更新到IE_Part_ProcessTime
                //List<string> lst1 = new List<string>();
                //lst1.Add("1");
                //BaseBuildSql.GetProDataTable("p_IE_IED_TransForm", lst1);
                SplashScreenTool.CloseSplashScreen();
               
            }
            catch
            {
                SplashScreenTool.CloseSplashScreen();
            }



        }

        //导出
        public override void DoExport(IButtonInfo sender)
        {
            try
            {
                SaveFileDialog dlg = new SaveFileDialog();
                //dlg.Filter = "PDF file(*.pdf)|*.pdf";
                dlg.Filter = "Excel文件(*.xls)|*.xls";
                DialogResult dialogResult = dlg.ShowDialog(this);
                if (dialogResult == DialogResult.OK)
                {
                    gridView2.ExportToXls(dlg.FileName);
                    DevExpress.XtraEditors.XtraMessageBox.Show("导出成功", "提示", MessageBoxButtons.OK);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void FrmBIEGroupPackageData_FormClosing(object sender, FormClosingEventArgs e)
        {

        }
    }
}
